package com.carbohydrate42.kotlin_compose_demo.compose

import android.app.Activity
import android.nfc.NfcAdapter
import android.nfc.Tag
import android.nfc.tech.Ndef
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.carbohydrate42.kotlin_compose_demo.util.DebugUtil


fun readNfcTag(tag: Tag): String {

    val ndef = Ndef.get(tag)
    return tag.techList.joinToString(", ")
}

/**
 * NFC读取, 参考
 * https://blog.csdn.net/scau_zhangpeng/article/details/79018778
 * http://www.nfchome.org/android-nfc-dev.html
 * https://blog.csdn.net/chaoyu168/article/details/98038569
 */
@Composable
@Preview(showBackground = true, showSystemUi = true)
fun TryNfc() {
    val context = LocalContext.current
    val nfc = NfcAdapter.getDefaultAdapter(context)
    var nfcInfo by remember {
        mutableStateOf("")
    }


    LaunchedEffect(Unit) {
        nfc?.let {
            nfc.enableReaderMode(
                context as Activity,
                { tag ->
                    DebugUtil.debugLog(
                        readNfcTag(tag)
                    )

                    nfcInfo = readNfcTag(tag)
                },
                NfcAdapter.FLAG_READER_NFC_A
                        or NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
                        or NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
                null
            )

        }
    }

    Column {
        Text(text = nfcInfo)
    }


}